package visiopuce.ui;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.eclipse.jface.bindings.keys.KeyStroke;
import org.eclipse.jface.bindings.keys.ParseException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.fieldassist.ContentProposalAdapter;
import org.eclipse.jface.fieldassist.SimpleContentProposalProvider;
import org.eclipse.jface.fieldassist.TextContentAdapter;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.nebula.widgets.formattedtext.NumberFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import visiopuce.ApplicationContexte;
import visiopuce.objets.FeuillePuce;
import visiopuce.objets.MarquePuce;
import visiopuce.objets.Puce;
import visiopuce.objets.TypePuce;
import visiopuce.objets.Utilisateur;
import visiopuce.service.FeuillePuceServiceImpl;
import visiopuce.service.PersonneServiceImpl;
import visiopuce.service.PuceServiceImpl;
import visiopuce.service.ReferentielServiceImpl;
import visiopuce.service.UtilisateurServiceImpl;
import visiopuce.service.document.ProtocolePuce;
import visiopuce.ui.providers.MarquePuceLabelProvider;
import visiopuce.ui.providers.TypePuceLabelProvider;
import visiopuce.ui.providers.UtilisateurLabelProvider;

public class FeuillePuceDialog extends Dialog {

	private FormattedText dTechnique;
	private ComboViewer comboMarquePuce;
	private ComboViewer comboModelePuce;
	private FormattedText tFeuillePuce;
	private Combo comboProtocolePuce;
	private ComboViewer comboTechnicienne;
	private Composite container;
	private Text[] tNom;
	private Group g;
	private Text tRemarque;
	private int nb = 8;
	private FeuillePuce fp;
	private ContentProposalAdapter[] adapter;
	private String typ = "";
	private Label[] lNom;

	public FeuillePuceDialog(Shell parent, FeuillePuce fp) {
		super(parent);
		this.fp = fp;
		setShellStyle(SWT.CLOSE | SWT.TITLE | SWT.BORDER | SWT.APPLICATION_MODAL);
		setBlockOnOpen(true);
	}

	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Création d'une feuille de travail de puce");
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		container = (Composite) super.createDialogArea(parent);
		container.setLayout(new GridLayout(2, false));

		Label lblDateDeLa = new Label(container, SWT.NONE);
		lblDateDeLa.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblDateDeLa.setText("Date de la technique :");

		dTechnique = new FormattedText(container, SWT.BORDER);
		dTechnique.setFormatter(new DateFormatter("dd/MM/yyyy"));
		GridData gridData_dTechnique = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
		gridData_dTechnique.widthHint = 75;
		dTechnique.getControl().setLayoutData(gridData_dTechnique);
		dTechnique.setValue(fp.getDateEnvoi());

		Label lblNumorDeLa = new Label(container, SWT.NONE);
		lblNumorDeLa.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblNumorDeLa.setText("Num\u00E9ro de la feuille puce :");

		tFeuillePuce = new FormattedText(container, SWT.BORDER);
		tFeuillePuce.setFormatter(new NumberFormatter(ApplicationContexte.nfEntier, Locale.FRENCH));
		tFeuillePuce.getControl().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		tFeuillePuce.setValue(fp.getIdFeuillePuce());
		tFeuillePuce.getControl().setEditable(false);

		Label lblRemarque = new Label(container, SWT.NONE);
		lblRemarque.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblRemarque.setText("Remarque :");

		tRemarque = new Text(container, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
		GridData gd_tInfoIndication = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
		gd_tInfoIndication.widthHint = 250;
		gd_tInfoIndication.heightHint = 96;
		tRemarque.setLayoutData(gd_tInfoIndication);
		if (fp.getRemarques() != null) {
			tRemarque.setText(fp.getRemarques());
		}

		// dTechnique = new Text(container, SWT.BORDER);
		// dTechnique.setFormatter(new DateFormatter("dd/MM/yyyy"));
		// GridData gridData_dTechnique = new GridData(SWT.LEFT, SWT.CENTER,
		// false, false, 1, 1);
		// gridData_dTechnique.widthHint = 75;
		// dTechnique.getControl().setLayoutData(gridData_dTechnique);

		Label lblMarqueDeLa = new Label(container, SWT.NONE);
		lblMarqueDeLa.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblMarqueDeLa.setText("Marque de la puce :");

		comboMarquePuce = new ComboViewer(container, SWT.DROP_DOWN | SWT.READ_ONLY);
		comboMarquePuce.setContentProvider(ArrayContentProvider.getInstance());
		comboMarquePuce.setLabelProvider(new MarquePuceLabelProvider());
		comboMarquePuce.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
		comboMarquePuce.setInput(ReferentielServiceImpl.getInstance().getMarquePuce());

		if (fp.getIdTypePuce() != 0) {
			comboMarquePuce.getCombo().setEnabled(false);
		} else {
			comboMarquePuce.addSelectionChangedListener(new ISelectionChangedListener() {

				@Override
				public void selectionChanged(SelectionChangedEvent event) {
					ISelection selectionMarque = comboMarquePuce.getSelection();
					MarquePuce marquePuceSel = null;
					if (!selectionMarque.isEmpty()) {
						IStructuredSelection structuredSelection = (IStructuredSelection) selectionMarque;
						marquePuceSel = (MarquePuce) structuredSelection.getFirstElement();
						if (comboModelePuce != null) {
							comboModelePuce.setInput(ReferentielServiceImpl.getInstance().getTypePuceByMarquePuce(marquePuceSel));
						}
					}

				}

			});
		}

		Label lblModleDeLa = new Label(container, SWT.NONE);
		lblModleDeLa.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblModleDeLa.setText("Mod\u00E8le de la puce :");

		comboModelePuce = new ComboViewer(container, SWT.DROP_DOWN | SWT.READ_ONLY);
		comboModelePuce.setContentProvider(ArrayContentProvider.getInstance());
		comboModelePuce.setLabelProvider(new TypePuceLabelProvider());
		comboModelePuce.getCombo().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

		TypePuce tp = ReferentielServiceImpl.getInstance().getTypePuceById(fp.getIdTypePuce());
		if (tp != null) {
			comboMarquePuce.setSelection(new StructuredSelection(tp.getMarquePuce()));
			MarquePuce marquePuceSel = null;
			if (!tp.getLibelle().isEmpty() && !comboMarquePuce.getSelection().isEmpty()) {
				ISelection selectionMarque = comboMarquePuce.getSelection();
				IStructuredSelection structuredSelection = (IStructuredSelection) selectionMarque;
				marquePuceSel = (MarquePuce) structuredSelection.getFirstElement();
				if (comboModelePuce != null) {
					comboModelePuce.setInput(ReferentielServiceImpl.getInstance().getTypePuceByMarquePuce(marquePuceSel));
				}
			}
			comboModelePuce.setSelection(new StructuredSelection(tp));
		}
		if (fp.getIdTypePuce() != 0) {
			comboModelePuce.getCombo().setEnabled(false);
		}
		Label lblModleDeProtocole = new Label(container, SWT.NONE);
		lblModleDeProtocole.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblModleDeProtocole.setText("Modèle de protocole :");

		comboProtocolePuce = new Combo(container, SWT.DROP_DOWN);
		comboProtocolePuce.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		if (fp.getProtocole() != null) {
			File file = new File(ApplicationContexte.REPERTOIRE_MODEL + "protocoles\\puce\\");
			File[] files = file.listFiles();
			comboProtocolePuce.removeAll();
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory() != true && (files[i].getName().contains(comboModelePuce.getCombo().getText()))) {
						comboProtocolePuce.add(files[i].getName());

					}
				}
			}
			comboProtocolePuce.setText(fp.getProtocole());
		}
		// ISelection selectionMarque = comboModelePuce.getSelection();
		// if (!selectionMarque.isEmpty()) {
		// File file = new File(ApplicationContexte.REPERTOIRE_MODEL +
		// "protocoles\\puce\\");
		// File[] files = file.listFiles();
		// if (comboProtocolePuce != null) {
		// comboProtocolePuce.removeAll();
		// if (files != null) {
		// for (int i = 0; i < files.length; i++) {
		// if (files[i].isDirectory() != true &&
		// (files[i].getName().contains(comboModelePuce.getCombo().getText())))
		// {
		// comboProtocolePuce.add(files[i].getName());
		//
		// }
		// }
		// }
		// }
		// }

		Label lblTechnicienne = new Label(container, SWT.NONE);
		lblTechnicienne.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
		lblTechnicienne.setText("Opérateur  :");

		comboTechnicienne = new ComboViewer(container, SWT.DROP_DOWN | SWT.READ_ONLY);
		comboTechnicienne.getControl().setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		comboTechnicienne.setContentProvider(ArrayContentProvider.getInstance());
		comboTechnicienne.setLabelProvider(new UtilisateurLabelProvider());
		ArrayList<Utilisateur> listTechniciennes = UtilisateurServiceImpl.getInstance().getTechnicienneByTypeAnalyse(3);
		if (listTechniciennes != null) {
			comboTechnicienne.setInput(listTechniciennes);
		}
		if (fp.getOperateur() != null) {
			comboTechnicienne.setSelection(new StructuredSelection(fp.getOperateur()));
		}

		File file = new File(ApplicationContexte.REPERTOIRE_PROTOCOLE);
		File[] files = file.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory() != true && (files[i].getName().contains("- N°" + fp.getIdFeuillePuce() + " - "))) {
					String message = "<a href=\"" + files[i].getName() + "\">" + files[i].getName() + "</a>";
					final Link lblLienDoc = new Link(container, SWT.NONE);
					lblLienDoc.setText(message);
					lblLienDoc.setToolTipText(files[i].getPath());
					lblLienDoc.getParent().pack();
					lblLienDoc.addSelectionListener(new SelectionListener() {

						@Override
						public void widgetSelected(SelectionEvent e) {
							try {
								File fichierResultat = new File(lblLienDoc.getToolTipText());
								Desktop desktop = Desktop.getDesktop();
								desktop.open(fichierResultat);
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}

						@Override
						public void widgetDefaultSelected(SelectionEvent e) {
							// TODO Auto-generated method stub

						}
					});
				}
			}
		}
		HashMap<String, Puce> puces = new HashMap<String, Puce>();
		if (fp.getIdFeuillePuce() > 0) {
			puces = PuceServiceImpl.getInstance().getPuceFromFeuillePuce(fp.getIdFeuillePuce());
		}
		g = new Group(container, SWT.BORDER);
		g.setText("Dossier de la puce");
		g.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
		g.setLayout(new GridLayout(4, false));

		if (tp != null && tp.getLibelle().contains("4x")) {
			nb = 4;
			tNom = new Text[4];
			lNom = new Label[4];
			adapter = new ContentProposalAdapter[4];
		} else {
			nb = 8;
			tNom = new Text[8];
			lNom = new Label[8];
			adapter = new ContentProposalAdapter[8];
		}
		if (fp.getIdTypePuce() == 13) {
			typ = "Agi8x60";
		}
		for (int i = 0; i < nb; i++) {
			createPersonneCombo();
		}
		setPersonnes(puces);
		if (fp.getIdTypePuce() != 0) {
			comboModelePuce.addSelectionChangedListener(new ISelectionChangedListener() {

				@Override
				public void selectionChanged(SelectionChangedEvent event) {
					ISelection selectionMarque = comboModelePuce.getSelection();
					if (!selectionMarque.isEmpty()) {
						File file = new File(ApplicationContexte.REPERTOIRE_MODEL + "protocoles\\puce\\");
						File[] files = file.listFiles();
						if (comboProtocolePuce != null) {
							comboProtocolePuce.removeAll();
							if (files != null) {
								for (int i = 0; i < files.length; i++) {
									if (files[i].isDirectory() != true && (files[i].getName().contains(comboModelePuce.getCombo().getText()))) {
										comboProtocolePuce.add(files[i].getName());

									}
								}
							}
						}
						IStructuredSelection structuredSelection = (IStructuredSelection) selectionMarque;
						TypePuce typePuce = (TypePuce) structuredSelection.getFirstElement();
						if (typePuce.getLibelle().contains("4x")) {
							nb = 4;
							typ = "";
							lNom = new Label[4];
							createPersonneCombo();
						} else {
							nb = 8;
							typ = "";
							if (typePuce.getLibelle().contains("8x60")) {
								typ = "Agi8x60";
							}
							lNom = new Label[8];
							createPersonneCombo();
						}

					}
				}

			});
		}
		return container;
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		Button bOk = createButton(parent, IDialogConstants.OK_ID, "Créer la feuille de travail", true);
		bOk.setToolTipText("Créer la feuille de manipulation de puce");
		Button bCl = createButton(parent, IDialogConstants.CANCEL_ID, "Annuler", false);
		bCl.setToolTipText("Annuler l'enregistrement");
	}

	@Override
	protected Point getInitialSize() {
		return new Point(1024, 500);
	}

	@Override
	protected void okPressed() {
		if (verifierChamp()) {
			fp.setChu("Montpellier");
			fp.setIdFeuillePuce(((Number) tFeuillePuce.getValue()).intValue());
			fp.setDateEnvoi((Date) dTechnique.getValue());
			ISelection selectiontec = comboTechnicienne.getSelection();
			if (!selectiontec.isEmpty()) {
				IStructuredSelection selection = (IStructuredSelection) selectiontec;
				Utilisateur operateur = (Utilisateur) selection.getFirstElement();
				fp.setOperateur(operateur);
			}

			ISelection selectionModel = comboModelePuce.getSelection();
			if (!selectionModel.isEmpty()) {
				IStructuredSelection selection = (IStructuredSelection) selectionModel;
				TypePuce typePuce = (TypePuce) selection.getFirstElement();
				fp.setIdTypePuce(typePuce.getIdTypePuce());
			}
			fp.setRemarques(tRemarque.getText());
			fp.setProtocole(comboProtocolePuce.getText());
			HashMap<String, Integer> numAnalyse = new HashMap<String, Integer>();
			for (int i = 0; i < nb; i++) {
				String nom = tNom[i].getText();
				int id = nom.lastIndexOf("°");
				if (id > 0) {
					String numAna = nom.substring(id + 1, nom.length());
					String[] tabllNom = lNom[i].getText().split(":");
					numAnalyse.put(tabllNom[1], Integer.parseInt(numAna));
				}
			}

			FeuillePuceServiceImpl.getInstance().save(fp, numAnalyse);
			if (fp.getIdTypePuce() == 13 || fp.getIdTypePuce() == 10) {
				ProtocolePuce protocole = new ProtocolePuce();
				String nomFichier = protocole.createDocument(fp);
				File fichierResultat = new File(nomFichier);
				Desktop desktop = Desktop.getDesktop();
				try {
					desktop.open(fichierResultat);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Fichier créé", "Le fichier " + nomFichier + " a bien été créé.");
			}
			super.okPressed();
		}
	}

	public FeuillePuce getFp() {
		return fp;
	}

	public void setFp(FeuillePuce fp) {
		this.fp = fp;
	}

	private boolean verifierChamp() {
		if (dTechnique.getValue() == null) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Champs obligatoire manquant", "Date de la technique");
			return false;
		}
		if (comboMarquePuce.getSelection().isEmpty()) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Champs obligatoire manquant", "Marque de la puce");
			return false;
		}
		if (comboModelePuce.getSelection().isEmpty()) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Champs obligatoire manquant", "Modèle de la puce");
			return false;
		}
		if (tFeuillePuce.getValue() == null) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Champs obligatoire manquant", "Numéro de la feuille");
			return false;
		}
		// Number numFeuille = (Number) tFeuillePuce.getValue();
		// FeuillePuce fp =
		// FeuillePuceServiceImpl.getInstance().getFeuillePuceById(numFeuille.intValue());
		// if (fp != null) {
		// MessageDialog.openError(Display.getCurrent().getActiveShell(),
		// "Duplication", "Le numéro de la feuille " + numFeuille +
		// " existe déjà dans la base.");
		// return false;
		// }
		if (comboTechnicienne.getSelection().isEmpty()) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Champs obligatoire manquant", "Opérateur");
			return false;
		}
		if (comboProtocolePuce.getText().isEmpty()) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Champs obligatoire manquant", "Protocole de la puce");
			return false;
		}
		return true;
	}

	private void setPersonnes(HashMap<String, Puce> puces) {
		for (int i = 0; i < tNom.length; i++) {
			String[] pp = lNom[i].getText().split(":");
			String numero = pp[1];
			Puce puce = puces.get(numero);
			SimpleContentProposalProvider scpNum = new SimpleContentProposalProvider(null);
			try {
				adapter[i] = new ContentProposalAdapter(tNom[i], new TextContentAdapter(), scpNum, KeyStroke.getInstance("Ctrl+Space"), null);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			adapter[i].setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
			tNom[i].addKeyListener(new NomKeyAdapter(i));
			if (puce != null) {
				tNom[i].setText(PersonneServiceImpl.getInstance().getPeronneAPasserPuceFromIdPuce(puce.getIdPuce()));
			}
			if (g != null) {
				g.reskin(SWT.ALL);
			}
		}
		g.pack();
		container.pack();
	}

	private void createPersonneCombo() {

		if (g == null) {
			g = new Group(container, SWT.BORDER);
			g.setText("Dossier de la puce");
			g.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
			g.setLayout(new GridLayout(4, false));
		} else {
			Control[] children = g.getChildren();
			for (Control control : children) {
				control.dispose();
			}
		}
		for (int j = 0; j < nb; j++) {

			lNom[j] = new Label(g, SWT.NONE);
			lNom[j].setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
			if (typ.equals("Agi8x60")) {
				if (j < 4) {
					lNom[j].setText("Individu:1_" + (j + 1));
				}
				if (j >= 4) {
					lNom[j].setText("Individu:2_" + (j - 3));
				}
			} else {
				lNom[j].setText("Individu:" + (j + 1));
			}

			tNom[j] = new Text(g, SWT.BORDER);
			GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
			gd.widthHint = 150;
			tNom[j].setLayoutData(gd);
			SimpleContentProposalProvider scpNum = new SimpleContentProposalProvider(null);
			try {
				adapter[j] = new ContentProposalAdapter(tNom[j], new TextContentAdapter(), scpNum, KeyStroke.getInstance("Ctrl+Space"), null);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			adapter[j].setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
			tNom[j].addKeyListener(new NomKeyAdapter(j));

		}
		if (g != null) {
			g.reskin(SWT.ALL);
		}
		g.pack();
		container.pack();
	}

	private void setAutoCompletion(String txt, int j) {
		try {
			String[] defaultProposals = PersonneServiceImpl.getInstance().getPeronneAPasserPuceFromString(txt);
			if (defaultProposals.length > 0) {
				((SimpleContentProposalProvider) adapter[j].getContentProposalProvider()).setProposals(defaultProposals);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private class NomKeyAdapter extends KeyAdapter {
		int j = -1;

		public NomKeyAdapter(int j) {
			this.j = j;
		}

		public void keyPressed(KeyEvent ke) {
			if (ke.keyCode == 262144) {
				setAutoCompletion(tNom[j].getText(), j);
			}
		}
	}

}
